package org.jef.codegen.template;

import pers.cz.codegen.codegen.CodeGenerator;
import pers.cz.codegen.dbtools.ColumnInfo;
import pers.cz.codegen.dbtools.MetaOperator;
import pers.cz.codegen.dbtools.TableInfo;
import pers.cz.codegen.describe.IClass;
import pers.cz.codegen.describe.JavaField;
import pers.cz.codegen.describe.JavaUnit;
import pers.cz.codegen.describe.SimpleClass;
import pers.cz.codegen.template.CommentTemplate;
import pers.cz.jefconfig.tools.StringUtils;

import java.io.File;
import java.lang.reflect.Modifier;
import java.nio.charset.Charset;
import java.sql.SQLException;

/*
 * @version 1.0
 * @description: 实体类代码生成
 * @author: ChengZhi 0336
 * @create: 2024-08-07 10:11
 */

public class EntityCodeGenerator extends CodeGenerator {

    private String tableName = "%";

    public EntityCodeGenerator(String tableName) {
        this.tableName = tableName;
    }

    public EntityCodeGenerator() {

    }

    /*
     * 自动生成实体代码
     * @throws SQLException
     */
    @Override
    public void generateCode() throws SQLException {

        MetaOperator metaOperator = new MetaOperator(tableName);
        for (TableInfo tableInfo : metaOperator.getAllTables()) {
            JavaUnit javaUnit = new JavaUnit(StringUtils.getCamelCase(tableInfo.getTableName().toLowerCase()));
            javaUnit.setIpackage(getIpackage());
            javaUnit.addImport("com.baomidou.mybatisplus.annotation.*");
            javaUnit.addImport("com.fasterxml.jackson.annotation.JsonIgnore");
            javaUnit.addImport("io.swagger.v3.oas.annotations.media.Schema");
            javaUnit.addImport("lombok.Data");
            javaUnit.setComment(CommentTemplate.classComment);
            javaUnit.setDescribe(tableInfo.getComment());
            javaUnit.addAnnotation("@Data");
            javaUnit.addAnnotation("@Schema(description = " + "\""+ tableInfo.getComment()+ "\"" +")");
            for (ColumnInfo columnInfo : tableInfo.getColumnInfos()) {
                String fieldName = StringUtils.getCamelCaseField(columnInfo.getCoulumnName().toLowerCase());
                String className = StringUtils.getCamelCase(columnInfo.getCoulumnName().toLowerCase());

                IClass simpleClass = new SimpleClass(columnInfo.getColumnType());
                JavaField javaField = new JavaField(fieldName);
                javaField.addReturnType(simpleClass);
                // 为常量添加注释
                javaField.setComment(columnInfo.getComment());
                // 为常量添加注解
                javaField.addAnnotation("@Schema(description = " + "\""+  columnInfo.getComment() + "\"" + ")");
                javaField.setModifer(Modifier.PRIVATE);

                javaUnit.addField(javaField);
            }
            File testFolder = new File(getFileFolder());
            javaUnit.saveToSrcFolder(testFolder, Charset.forName("UTF8"));
        }
    }

    @Override
    public void enhanceCode() throws Exception {

    }
}
